package com.binguo.api.baidu;

import com.alibaba.fastjson.JSONArray;
import com.binguo.api.webapi_tts.FileUtil;
import com.binguo.youtu.sign.Base64Util;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class BaiduPicService {/*
    private static String appid = "16799576";
    private static String apiKey = "yjMk5nNCXrypph2OsD5uFiOG";
    private static String securityKey = "zsrYkcz3fX3ZGz28ZAgusPP8T6elKHqO";
*/
    private static String appid = "16805085";
    private static String apiKey = "3t7PQUPeThDcPyEpUNh8UHZA";
    private static String securityKey = "SciYNqyHOip2GnS5jDjw5nCgeaqFA85w";


    public static void main(String[] args) throws Exception{
        long l = System.currentTimeMillis();
        System.out.println(l);
//        detection("/Users/jay/IdeaProjects/binguo/api/target/1562377593903.jpg");
        search();
//        realtime_searchAdd();
//        temp();
        System.out.println(System.currentTimeMillis() - l);
    }

    public static void search()throws Exception{
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=" + URLEncoder.encode(
                getAuth());

        String filename = "/Users/jay/IdeaProjects/binguo/api/target/1563157559577.jpg";

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        String filePath = filename;
        byte[] imgData = FileUtil.read(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam + "&top_num=" + 5;


        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void temp()throws Exception{
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=" + URLEncoder.encode(
                getAuth());

        String filename = "/Users/jay/IdeaProjects/binguo/api/target/1563161370392.jpg";
//        String filename = "/Users/jay/IdeaProjects/binguo/api/target/1562679047195.jpg";

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        String filePath = filename;
        byte[] imgData = FileUtil.read(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam + "&top_num=" + 5;


        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void testa(){

    }

    public static void realtime_searchAdd()throws Exception{
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/add?access_token=" + URLEncoder.encode(
                getAuth());

        String filename = "/Users/jay/IdeaProjects/binguo/api/target/1563269246815.jpg";
//        String filename = "/Users/jay/IdeaProjects/binguo/api/target/1563157559577.jpg";

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        String filePath = filename;
        byte[] imgData = FileUtil.read(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam + "&sub_lib=" + appid + "&brief=doufu";

        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 检测
     */
    public static void detection(String filename){
        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/yunpeng?access_token=" + URLEncoder.encode(
        getAuth());

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("image", ImageBase64Util.getImageBinary(filename));
        String requestBody = json.toJSONString();

        System.out.println(requestBody);
        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());
        } catch (Exception e) {

        }
    }


    /**
     * 数据集创建API
     */
    public static void createDataSet(){
        String url = "https://aip.baidubce.com/rpc/2.0/easydl/dataset/create?access_token=" + URLEncoder.encode(
        getAuth());

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("type", "OBJECT_DETECTION");
        json.put("dataset_name", "yunpeng12");
        String requestBody = json.toJSONString();

        System.out.println(requestBody);
        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());
        } catch (Exception e) {

        }
    }

    /**
     * 数据集列表API
     */
    public static void datasetList(){
        String url = "https://aip.baidubce.com/rpc/2.0/easydl/dataset/list?access_token=" + URLEncoder.encode(
        getAuth());

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("type", "OBJECT_DETECTION");
        String requestBody = json.toJSONString();

        System.out.println(requestBody);
        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());

            /**
             * {"total_num":2,"results":[{"dataset_id":38898,"dataset_name":"test","type":"OBJECT_DETECTION","status":"normal","special_status":""},{"dataset_id":38909,"dataset_name":"yunpeng12","type":"OBJECT_DETECTION","status":"normal","special_status":""}],"log_id":538141525}
             */
        } catch (Exception e) {

        }
    }

    /**
     * 添加数据API
     */
    public static void datasetAddentity(String filename){
        String url = "https://aip.baidubce.com/rpc/2.0/easydl/dataset/addentity?access_token=" + URLEncoder.encode(
        getAuth());

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("type", "OBJECT_DETECTION");
        json.put("dataset_id", "38909");
        json.put("entity_content", ImageBase64Util.getImageBinary(filename));
        json.put("entity_name", filename);
        com.alibaba.fastjson.JSONObject label = new com.alibaba.fastjson.JSONObject();
        label.put("label_name", "yurou");
        label.put("left", 211);
        label.put("top", 32);
        label.put("width", 200);
        label.put("height", 200);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(label);
        json.put("labels", jsonArray);
        String requestBody = json.toJSONString();

        System.out.println(requestBody);
        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());

            /**
             * {"total_num":2,"results":[{"dataset_id":38898,"dataset_name":"test","type":"OBJECT_DETECTION","status":"normal","special_status":""},{"dataset_id":38909,"dataset_name":"yunpeng12","type":"OBJECT_DETECTION","status":"normal","special_status":""}],"log_id":538141525}
             */
        } catch (Exception e) {

        }
    }
    /**
     * 数据集删除API
     */
    public static void datasetDelete(String dataset_id){
        String url = "https://aip.baidubce.com/rpc/2.0/easydl/dataset/delete?access_token=" + URLEncoder.encode(
        getAuth());

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("type", "OBJECT_DETECTION");
        json.put("dataset_id", dataset_id);

        String requestBody = json.toJSONString();

        System.out.println(requestBody);
        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());

            /**
             */
        } catch (Exception e) {

        }
    }

    /**
     * 分类（标签）删除API
     */
    public static void labelDelete(String dataset_id, String label_name){
        String url = "https://aip.baidubce.com/rpc/2.0/easydl/label/delete?access_token=" + URLEncoder.encode(
        getAuth());

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("type", "OBJECT_DETECTION");
        json.put("dataset_id", dataset_id);
        json.put("label_name", label_name);

        String requestBody = json.toJSONString();

        System.out.println(requestBody);
        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());

            /**
             */
        } catch (Exception e) {

        }
    }

    /**
     * 分类（标签）列表API
     */
    public static void getLabelList(){
        String url = "https://aip.baidubce.com/rpc/2.0/easydl/label/list?access_token=" + URLEncoder.encode(
                getAuth());

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);

        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("type", "OBJECT_DETECTION");
        json.put("dataset_id", "38909");
        String requestBody = json.toJSONString();

        System.out.println(requestBody);
        try {
            HttpEntity<String> entity = new HttpEntity<>(requestBody, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());

            //{"total_num":0,"results":[],"log_id":2277705644}
        } catch (Exception e) {

        }
    }

    /**
     * 获取权限token
     * @return 返回示例：
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = apiKey;
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = securityKey;
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }


}
